package com.framework.mybatis.typehandle;

import cn.hutool.core.util.StrUtil;
import com.framework.common.utils.AESUtils;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;

import java.sql.*;

/**
 * @author lihanbo
 * @version 1.0
 * @date 2022/2/8 15:11
 */
@MappedTypes({String.class})
@MappedJdbcTypes({JdbcType.VARCHAR})
public class AESEncryptHandler extends BaseTypeHandler<String> {


    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, String parameter, JdbcType jdbcType) throws SQLException {
        if (StrUtil.isEmpty(parameter)) {
            ps.setNull(i, Types.VARCHAR);
        } else {
            ps.setString(i, AESUtils.encrypt(parameter));
        }
    }

    @Override
    public String getNullableResult(ResultSet rs, String columnName) throws SQLException {
        String columnValue = rs.getString(columnName);
        if (rs.wasNull()) {
            return null;
        }
        try {
            return AESUtils.decrypt(columnValue);
        } catch (Exception e) {
            return columnValue;
        }
    }

    @Override
    public String getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        String columnValue = cs.getString(columnIndex);
        if (cs.wasNull()) {
            return null;
        }
        try {
            return AESUtils.decrypt(columnValue);
        } catch (Exception e) {
            return columnValue;
        }
    }

    @Override
    public String getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        String columnValue = rs.getString(columnIndex);
        if (rs.wasNull()) {
            return null;
        }
        try {
            return AESUtils.decrypt(columnValue);
        } catch (Exception e) {
            return columnValue;
        }
    }
}
